import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.template
import time
from tornado.escape import json_encode
from postboardapp_redis import *
import os
import sys
import tornado.auth

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    "xsrf_cookies": True,
    "login_url":"/auth/login",
}
def gen_table(node,depth, backid):
    #print node
    if node == None or node['isdel'] == 1:  return ''
    ret = '<table border="0">'
    for n in node['nodes']:
        subnode = get_node(n['id'])
        if subnode['isdel'] == 1: continue
#        print subnode
        ret += '<tr>%s<td><a class="titlelink" href="/node?nodeid=%s">%s</a> <span class="info">by %s @ %s</span> | <a href="/newpost?nodeid=%s&type=comment&backid=%s"><img src="/static/reply.png" /></a><div class="replycontect-desc">%s</div> %s</td></tr>\n' % (
                '<td class="blank"></td>' * 1 ,
                subnode['id'],
                subnode['title'], 
                subnode['username'],
                subnode['isdel'],
                subnode['id'],
                backid,
                subnode['content'],
                gen_table(subnode,depth+1, backid)
            )
    ret += '</table>'
    return ret


class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        user_json = self.get_secure_cookie("user")
        if not user_json: return None
        return tornado.escape.json_decode(user_json)

class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    @tornado.web.asynchronous
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect(ax_attrs=["email"])

    def _on_auth(self, user):
        if not user:
            raise tornado.web.HTTPError(500, "Google auth failed")
        self.set_secure_cookie("user", tornado.escape.json_encode(user))
        self.redirect("/")

class LogoutHandler(BaseHandler):
    def get(self):
        self.clear_cookie("user")
        self.redirect("/")

class IndexHandler(BaseHandler):
    def get(self):
        t = get_threads(sort='id')
        self.render("./template/index.html", threads = t)
        return

class NewPostHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _backid = self.get_argument('backid','-1')
        _nodeid = self.get_argument('nodeid','0')
        _posttype = self.get_argument('type','thread')
        _username = self.get_current_user()
        _node = None
        _title = None
        if _posttype != 'thread':
            _node = get_node(_nodeid)
            _title = "Re:" + _node['title']
        self.render("./template/post.html", backid = _backid, nodeid = _nodeid, posttype = _posttype, node= _node , title = _title, name=_username['name'])
        
    @tornado.web.authenticated
    def post(self):
        posttype = self.get_argument('type','thread')
        backid = self.get_argument('backid','-1')
        name = self.get_current_user()['name']
#        name = self.get_argument('name','guest')
        title = self.get_argument('title','untitled')
        content = self.get_argument('content',' ')
        nodeid = self.get_argument('nodeid','0')

        if posttype == 'thread':
            newnode = new_thread(title,content,username=name)
            self.redirect("/node?nodeid=" + newnode['id'])
        else:
            new_comment(nodeid, title, content, username=name)
            self.redirect("/node?nodeid=" + backid)
        return

class NodeHandler(BaseHandler):
#    @tornado.web.authenticated
    def get(self):
        nodeid = self.get_argument('nodeid')
        if len(nodeid) == 0 or nodeid == -1: 
            self.redirect('/')
            return
        node = get_node(nodeid)
        if node is None or node['isdel'] == 1:
            self.redirect('/')
            return
        _comment_table = gen_table(node, 1, node['id'])
        self.render("./template/node.html",node=node, table = _comment_table)

class UploadHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
	    self.set_header("Content-Type", "text/plain")
	    file1 = self.request.files['imgFile'][0]
	    ext_name = file1['filename'].split('.')[-1]
	    if ext_name not in ('jpg','png','bmp','gif','jpeg'):
	        self.write(json_encode({'error':1, 'message':u'File type not support!'}))
	        return 
	    filename = str(int(time.mktime(datetime.datetime.now().timetuple()))) + '.' + ext_name
	    output_file = open("./static/uploads/" + filename, 'w')
	    output_file.write(file1['body'])
	    output_file.close()
	    self.write(json_encode({'error':0, 'url':'/static/uploads/' + filename}))
        
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')
        
application = tornado.web.Application([
    (r"/", IndexHandler),
    (r"/newpost", NewPostHandler),
    (r"/node", NodeHandler),
    (r"/upload", UploadHandler),
    (r"/auth/login", AuthHandler),
    (r"/auth/logout", LogoutHandler),
#    (r"/favicon.ico", FaviconHandler)
], **settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
